import 'package:airbnb_clone/internal/sqlite/core/engine.dart';
import 'package:airbnb_clone/models/user_message.dart';
import 'package:sqflite_common_ffi/sqflite_ffi.dart';

class MessageDao {
  final SqilteEngine _sqilteEngine = SqilteEngine();
  Database? _database;
  String tableName = "message";
  MessageDao() {
    _initDatabse();
  }
  // 初始化数据库连接

  Future _initDatabse() async {
    _database = await _sqilteEngine.initMessageDatabase();
    return _database;
  }

  // 插入数据
  Future insertData(UserMessage userMessage) async {
    _database = await _initDatabse();
    return await _database?.insert(tableName, {
      "senderId": userMessage.senderId,
      "receptorId": userMessage.receptorId,
      "userName": userMessage.userName,
      "userImg": userMessage.userImg,
      "context": userMessage.context,
      "create_time": DateTime.now().toIso8601String()
    });
  }

  // 查询所有数据
  Future<List<UserMessage>> getAllData(int receptorId, int senderId) async {
    _database = await _initDatabse();
    List<Map<String, dynamic>>? maps = await _database?.query(tableName,
        where: '''(senderId = ? AND  receptorId = ?)
         OR
             (senderId = ? AND  receptorId = ?)''',
        whereArgs: [receptorId, senderId, senderId, receptorId]);
    if (maps == null) {
      return [];
    }
    List<UserMessage> messageList = [];
    for (var element in maps) {
      messageList.add(UserMessage(
          id: element["id"],
          senderId: element["senderId"],
          receptorId: element["receptorId"],
          userName: element["userName"],
          userImg: element["userImg"],
          context: element["context"],
          createTime: DateTime.parse(element["create_time"])));
    }
    return messageList;
    // return List.generate(maps!.length, (index) {
    //   Map<String, dynamic> element = maps[index];
    //   return UserMessage(
    //       id: element["id"],
    //       senderId: element["senderId"],
    //       receptorId: element["receptorId"],
    //       userName: element["username"],
    //       userImg: element["userImg"],
    //       context: element["context"],
    //       createTime: element["create_time"]);
    // });
  }

  // 删除所有数据
  Future deleteAllData() async {
    _database = await _initDatabse();
    return await _database?.delete(tableName, where: "id > ?", whereArgs: [0]);
  }
}
